package com.ewhale.feitengguest.ui.shop.deal

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cc.shinichi.library.ImagePreview
import com.ewhale.feitengguest.R
import com.ewhale.feitengguest.dto.MyTaskDetailDto
import com.ewhale.feitengguest.dto.SubmitDetailDto
import com.ewhale.feitengguest.presenter.shop.deal.HandlerTaskPresenter
import com.ewhale.feitengguest.ui.user.mine.adapter.ContentAdapter
import com.ewhale.feitengguest.ui.user.mine.adapter.ShowImageAdapter
import com.ewhale.feitengguest.view.shop.deal.HandlerTaskView
import com.simga.library.activity.MBaseActivity
import com.simga.library.utils.CheckUtil
import com.simga.library.utils.DateUtil
import com.simga.library.utils.LogUtil
import com.simga.library.utils.glide.GlideUtil
import com.simga.library.widget.HintDialog
import kotlinx.android.synthetic.main.activity_handler_task.*
import java.util.*

class HandlerTaskActivity : MBaseActivity<HandlerTaskPresenter>(), HandlerTaskView {
    override fun getViewId(): Int {
        return R.layout.activity_handler_task
    }

    override fun isUseBaseTitleBar(): Boolean {
        return true
    }

    private var taskId: Long? = null
    private var mMyTime: MyTime? = null
    private var detailsDto: SubmitDetailDto? = null
    private val contentList = ArrayList<MyTaskDetailDto.ContentExplainDtosBean>()
    private var contentAdapter: ContentAdapter? = null
    private var mImageAdaoter: ShowImageAdapter? = null
    private val showImage = ArrayList<String>()//提交后展示的图片

    override fun init(savedInstanceState: Bundle?) {
        setTitle("提交信息")

        contentAdapter = ContentAdapter(contentList, false)
        mImageAdaoter = ShowImageAdapter(showImage, false)

        lv_showContent.apply {
            adapter = contentAdapter
            layoutManager = object : LinearLayoutManager(mContext, RecyclerView.VERTICAL, false) {
                override fun canScrollVertically() = false
            }
            isNestedScrollingEnabled = false
            setHasFixedSize(false)
            isFocusable = false
        }
        gv_image_msg.apply {
            adapter = mImageAdaoter
            layoutManager = GridLayoutManager(mContext, 3)
        }
        presenter.loadSubmitDetail(taskId!!)
    }

    override fun initListener() {
        super.initListener()
        btn_handle_1.setOnClickListener {
            if (ll_unAgree.visibility != View.VISIBLE) {
                ll_unAgree.visibility = View.VISIBLE
            }
        }
        btn_handle_2.setOnClickListener {
            val hintDialog = HintDialog(mContext, "提示", "您确定通过该用户提交任务吗？", arrayOf("取消", "确定"))
            hintDialog.setCallback(object : HintDialog.Callback {
                override fun callback() {
                    presenter!!.agreeOrUnAgree(detailsDto!!.id, 3, "")
                }
                override fun cancle() {}
            })
            hintDialog.show()
        }
        btn_unAgree.setOnClickListener {
            if(et_refuseReason.text.isEmpty()){
                showToast("请输入驳回理由")
                return@setOnClickListener
            }
            val hintDialog = HintDialog(mContext, "提示", "您确定驳回该用户提交任务吗？", arrayOf("取消", "确定"))
            hintDialog.setCallback(object : HintDialog.Callback {
                override fun callback() {
//                    LogUtil.e("JIA","--et_content : " + et_refuseReason.text.toString())
                    presenter!!.agreeOrUnAgree(detailsDto!!.id, 2, et_refuseReason.text.toString())
                }
                override fun cancle() {}
            })
            hintDialog.show()
        }
        mImageAdaoter!!.setOnItemClickListener { view, position ->
            ImagePreview.getInstance().setContext(mContext)
                    .setIndex(position)
                    .setShowDownButton(false)
                    .setImageList(showImage)
                    .setLoadStrategy(ImagePreview.LoadStrategy.AlwaysOrigin)
                    .setZoomTransitionDuration(300)
                    .setEnableDragClose(true)
                    .setErrorPlaceHolder(R.drawable.default_image).start()
        }
    }

    override fun updateTaskDetail(status: Int) {
        mMyTime!!.cancel()
        mMyTime = null
        sendBroadcast(Intent("UPDATE_SUBMIT_LIST"))
        if (status == 3) {
            showToast("任务已通过")
        } else{
            showToast("任务已驳回")
        }
        presenter!!.loadSubmitDetail(taskId!!)
    }

    override fun showSubmitDetails(detailsDto: SubmitDetailDto) {
        this.detailsDto = detailsDto
        GlideUtil.loadPicture(detailsDto.headPhoto, iv_avatar, R.drawable.default_image)
        ll_unAgree.visibility = View.GONE
        when (detailsDto.status) {
            1 -> {
                tv_refuseCause.visibility = View.GONE
                ll_handle.visibility = View.VISIBLE
                iv_status.visibility = View.GONE
                if (detailsDto.authEndTime > 0) run {
                    val countDown = (detailsDto.authEndTime * 1000 - Date().time) / 1000
                    mMyTime = MyTime(countDown * 1000, 1000)
                    mMyTime!!.start()
                }
            }
            else -> {
                ll_handle.visibility = View.GONE
                iv_status.visibility = View.VISIBLE
                tv_over_time.text = detailsDto.updateTime
                when (detailsDto.status) {
                    2 -> {
                        tv_refuseCause.visibility = View.VISIBLE
                        tv_refuseCause.text = "不通过原因："+ detailsDto.refuseCause
                        iv_status.setImageResource(R.mipmap.d3_ic_shbtg)
                    }
                    3 -> {
                        tv_refuseCause.visibility = View.GONE
                        iv_status.setImageResource(R.mipmap.d3_ic_shtg)
                    }
                    4 -> {
                        tv_refuseCause.visibility = View.GONE
                        iv_status.setImageResource(R.mipmap.d3_ic_ygq)
                    }
                }
            }
        }
        tv_task_title.text = "任务：" + detailsDto.title
        tv_price.text = "￥" + detailsDto.unitPrice.stripTrailingZeros().toPlainString()
        tv_name.text = detailsDto.nickName
        tv_creat_time.text = detailsDto.createTime

        contentList.clear()
        if (detailsDto.contentExplain.size > 0) {
            for (i in 0 until detailsDto.contentExplain.size) {
                when (i) {
                    0 -> detailsDto.contentExplain[i].content = detailsDto.content1
                    1 -> detailsDto.contentExplain[i].content = detailsDto.content2
                    2 -> detailsDto.contentExplain[i].content = detailsDto.content3
                    3 -> detailsDto.contentExplain[i].content = detailsDto.content4
                    4 -> detailsDto.contentExplain[i].content = detailsDto.content5
                }
            }
        }
        contentList.addAll(detailsDto.contentExplain)
        contentAdapter!!.notifyDataSetChanged()
        when {
            detailsDto.submitType == 1 -> {//图文
                tv_pic_info.visibility = View.VISIBLE
                gv_image_msg.visibility = View.VISIBLE
                tv_pic_info.text = detailsDto.imgExplain
                if (!CheckUtil.isNull(detailsDto.imgUrls)) {
                    showImage.clear()
                    showImage.addAll(detailsDto.imgUrls.split(",".toRegex()))
                    mImageAdaoter!!.notifyDataSetChanged()
                }
            }
            detailsDto.submitType == 2 -> {//文字
                tv_pic_info.visibility = View.GONE
                tv_pic_info.visibility = View.GONE
            }
            else -> {//图片
                tv_pic_info.visibility = View.VISIBLE
                tv_pic_info.visibility = View.VISIBLE
                tv_pic_info.text = detailsDto.imgExplain
                if (!CheckUtil.isNull(detailsDto.imgUrls)) {
                    showImage.clear()
                    showImage.addAll(detailsDto.imgUrls.split(",".toRegex()))
                    mImageAdaoter!!.notifyDataSetChanged()
                }
            }
        }
    }

    private inner class MyTime(millisInFuture: Long, countDownInterval: Long) : CountDownTimer(millisInFuture, countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            tv_over_time.text = DateUtil.formatSeconds(millisUntilFinished / 1000) + "后自动审核通过"
        }

        override fun onFinish() {//结束了，重新刷新UI
            presenter.loadSubmitDetail(taskId!!)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mMyTime = null
    }
    override fun showProLoading() {
        showLoading()
    }

    override fun dimissProLoading() {
        dismissLoading()
    }

    override fun showErrorMessage(postCode: Int, code: String, message: String) {
        showErrorMsg(code, message)
    }

    companion object {
        fun open(mContext: MBaseActivity<*>, taskId: Long) {
            val bundle = Bundle()
            bundle.putLong("taskId", taskId)
            mContext.startActivity(bundle, HandlerTaskActivity::class.java)
        }
    }

    override fun onGetBundle(bundle: Bundle) {
        taskId = bundle.getLong("taskId")
    }
}
